import java.io.FileInputStream;
import java.security.MessageDigest;
 
public class SHAChecksum {
	 public String getStringSHAChecksum(String filename) throws Exception{
	 MessageDigest md = MessageDigest.getInstance("SHA-256");
	 FileInputStream fis = new FileInputStream(filename);
	 
	 byte[] dataBytes = new byte[1024];
	 
	 int nread = 0;
	 while ((nread = fis.read(dataBytes)) != -1) {
	  md.update(dataBytes, 0, nread);
	 };
	 byte[] mdbytes = md.digest();
	 
	 //convert the byte to hex format
	 StringBuffer sb = new StringBuffer();
	 for (int i = 0; i < mdbytes.length; i++) {
	  sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
	 }
	 
	 /*System.out.println("Hex format : " + sb.toString());
	 System.out.println("Hex format length : " + sb.toString().length());
	 System.out.println("MD length : " + mdbytes.length);*/
	 return sb.toString();
	 }
	 /*
	 public static byte[] getMdSHAChecksumString(String sb) throws NoSuchAlgorithmException {
		 MessageDigest md = MessageDigest.getInstance("SHA-256");
		 ByteBuffer fis = ByteBuffer.wrap(sb.getBytes());
		 
		// byte[] dataBytes = new byte[1024];	 
		 
		 while (fis.position() < fis.capacity()) {
			 md.update(fis.get());
		 };
		 byte[] mdbytes = md.digest();
		 
		 return mdbytes;
	 }*/
	 
	 public byte[] getMdSHAChecksum(String filename) throws Exception{
		 MessageDigest md = MessageDigest.getInstance("SHA-256");
		 FileInputStream fis = new FileInputStream(filename);
		 
		 byte[] dataBytes = new byte[1024];
		 
		 int nread = 0;
		 while ((nread = fis.read(dataBytes)) != -1) {
		  md.update(dataBytes, 0, nread);
		 };
		 byte[] mdbytes = md.digest();
		 
		 //convert the byte to hex format
		 StringBuffer sb = new StringBuffer();
		 for (int i = 0; i < mdbytes.length; i++) {
		  sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
		 }
		 
		 /*System.out.println("Hex format : " + sb.toString());
		 System.out.println("Hex format length : " + sb.toString().length());
		 System.out.println("MD length : " + mdbytes.length);*/
		 return mdbytes;
		 }
	 
	 public static String byteToHex(byte[] mdbytes) {
		 StringBuffer sb = new StringBuffer();
		 for (int i = 0; i < mdbytes.length; i++) {
		  sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
		 }	
		 return sb.toString();
	 }
} 
